//var baseUrl = 'http://192.168.110.108:8080';
var baseUrl = 'http://localhost:9001';
var loginUser = JSON.parse(sessionStorage.getItem('member'));

reloadMember();

$('.login').click(function(){
	var dialog = new bDialog();
	dialog.open({
		title: '会员登录',
		html: $('#login').html(),
	});
});

$('.change').click(function(){
	var dialog = new bDialog();
	dialog.open({
		title: '切换账号',
		html: $('#login').html(),
	});
});

$('html').on('submit', '.loginForm', function(){
	var phone = $(this).find('input[name="phone"]').val();
	var password = $(this).find('input[name="password"]').val();

	console.log({phone, password});
	$.ajax({
		url: baseUrl + '/fore/member/login',
		data: JSON.stringify({password,phone}),
		contentType: 'application/json; charset=UTF-8',
		type: 'post',
		dataType: 'JSON',
		success(result){
			if (result.code == 200){
				sessionStorage.setItem('token', result.msg);
				sessionStorage.setItem('member', JSON.stringify(result.data));
				loginUser = result.data;
				// 刷新界面
				reloadMember();
				$('.dialog').remove();
			} else {
				new bDialog().open({
					title: '警告',
					html: result.msg,
				});
			}
		},
	});

	return false;
});

function reloadMember(){
	console.log(loginUser);

	if (loginUser != null) {
		// 刷新界面
		$('.infos .id .info').text(loginUser.id)
		$('.infos .phone .info').text(loginUser.phone)
		$('.infos .name .info').text(loginUser.name)
		$('.infos .balance .info').text(loginUser.balance)
		$('.login').hide();
		$('.change').show();
		$('.logout').show();
	} else {
		$('.infos .id .info').text('未登录')
		$('.infos .phone .info').text('未登录')
		$('.infos .name .info').text('未登录')
		$('.infos .balance .info').text('未登录')
		$('.login').show();
		$('.change').hide();
		$('.logout').hide();
	}
}


$('.logout').click(function(){
	// 清除数据
	sessionStorage.removeItem('token');
	sessionStorage.removeItem('member');
	loginUser = null;
	reloadMember()
});
// 注册表单提交处理
$('html').on('submit', '.addForm', function(){
	var form = $(this);
	var name = form.find('input[name="name"]').val().trim();
	var phone = form.find('input[name="phone"]').val().trim();
	var password = form.find('input[name="password"]').val().trim();
	var balance = form.find('input[name="balance"]').val().trim();

	// 简单前端验证
	if (!name) {
		showError(form, 'name', '请输入会员名字');
		return false;
	}
	if (name.length < 2 || name.length > 10) {
		showError(form, 'name', '长度在 2 到 10 个字符');
		return false;
	}

	if (!phone) {
		showError(form, 'phone', '请输入会员电话');
		return false;
	}
	if (!/^1[3-9]\d{9}$/.test(phone)) {
		showError(form, 'phone', '请输入正确的手机号码');
		return false;
	}

	if (!password) {
		showError(form, 'password', '请输入密码');
		return false;
	}
	if (password.length < 1 || password.length > 16) {
		showError(form, 'password', '长度在 1 到 16 个字符');
		return false;
	}

	if (balance && !/^[1-9]\d*$/.test(balance)) {
		showError(form, 'balance', '请输入正整数金额');
		return false;
	}

	// 清除所有错误提示
	clearErrors(form);

	// 准备提交数据
	var memberData = {
		name: name,
		phone: phone,
		password: password
	};

	// 如果有充值金额，转换为数字
	if (balance) {
		memberData.balance = parseInt(balance);
	}

	$.ajax({
		url: baseUrl + '/fore/member/reg',
		data: JSON.stringify(memberData),
		contentType: 'application/json; charset=UTF-8',
		type: 'post',
		dataType: 'JSON',
		success(result) {
			if (result.code == 200) {
				// 注册成功后自动登录
				$.ajax({
					url: baseUrl + '/fore/member/login',
					data: JSON.stringify({phone: phone, password: password}),
					contentType: 'application/json; charset=UTF-8',
					type: 'post',
					dataType: 'JSON',
					success(loginResult) {
						if (loginResult.code == 200) {
							sessionStorage.setItem('token', loginResult.msg);
							sessionStorage.setItem('member', JSON.stringify(loginResult.data));
							loginUser = loginResult.data;
							// 刷新界面
							reloadMember();
							$('.dialog').remove();

							// 显示成功消息
							new bDialog().open({
								title: '成功',
								html: '注册成功并已自动登录！',
							});
						} else {
							// 登录失败，只关闭注册对话框
							$('.dialog').remove();
							new bDialog().open({
								title: '警告',
								html: '注册成功但自动登录失败，请手动登录',
							});
						}
					}
				});
			} else {
				new bDialog().open({
					title: '警告',
					html: result.msg || '注册失败',
				});
			}
		},
		error() {
			new bDialog().open({
				title: '错误',
				html: '服务器繁忙，注册失败',
			});
		}
	});

	return false;
});
const editRules = {
	name: [
		{ required: true, message: '请输入会员名字', trigger: 'blur' },
		{ min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
	],
	phone: [
		{ required: true, message: '请输入会员电话', trigger: 'blur' },
		{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
	],
	password: [
		{ min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur' }
	],
	newPassword: [
		{ min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur' }
	]
};

$('.fix').click(function() {
	if (!loginUser) {
		new bDialog().open({
			title: '警告',
			html: '请先登录！',
		});
		return;
	}

	// 先获取编辑表单HTML
	var editHtml = $('#edit').html();

	var dialog = new bDialog();
	dialog.open({
		title: '修改会员信息',
		html: editHtml,

	});

	// 手动延迟执行以确保对话框已创建
	setTimeout(function() {
		var form = $('.editForm');
		form.find('input[name="id"]').val(loginUser.id);
		form.find('input[name="name"]').val(loginUser.name);
		form.find('input[name="phone"]').val(loginUser.phone);
		form.find('input[name="balance"]').val(loginUser.balance);
		clearErrors(form);
	}, 50);
});

// 修改表单提交处理
$('html').on('submit', '.editForm', function() {
	var form = $(this);
	var id = form.find('input[name="id"]').val();
	var name = form.find('input[name="name"]').val().trim();
	var phone = form.find('input[name="phone"]').val().trim();
	var password = form.find('input[name="password"]').val().trim();
	var newPassword = form.find('input[name="newPassword"]').val().trim();
	var balance = parseInt(form.find('input[name="balance"]').val().trim())

	// 前端验证
	if (!name) {
		showError(form, 'name', '请输入会员名字');
		return false;
	}
	if (name.length < 2 || name.length > 10) {
		showError(form, 'name', '长度在 2 到 10 个字符');
		return false;
	}

	if (!phone) {
		showError(form, 'phone', '请输入会员电话');
		return false;
	}
	if (!/^1[3-9]\d{9}$/.test(phone)) {
		showError(form, 'phone', '请输入正确的手机号码');
		return false;
	}

	if (password && (password.length < 1 || password.length > 16)) {
		showError(form, 'password', '长度在 1 到 16 个字符');
		return false;
	}

	if (newPassword && (newPassword.length < 1 || newPassword.length > 16)) {
		showError(form, 'newPassword', '长度在 1 到 16 个字符');
		return false;
	}
	if (!balance) {
		showError(form, 'balance', '请输入充值金额');
		return false;
	}
	if (balance && !/^[1-9]\d*$/.test(balance)) {
		showError(form, 'balance', '请输入正整数金额');
		return false;
	}

	// 清除所有错误提示
	clearErrors(form);

	// 准备提交数据
	var memberData = {
		id: id,
		name: name,
		phone: phone,
		balance: balance
	};

	// 只有当密码不为空时才添加密码字段
	if (password) {
		memberData.password = password;
	}
	if (newPassword) {
		memberData.newPassword = newPassword;
	}

	$.ajax({
		url: baseUrl + '/fore/member/edit',
		data: JSON.stringify(memberData),
		contentType: 'application/json; charset=UTF-8',
		type: 'put',
		dataType: 'JSON',
		success(result) {
			if (result.code == 200) {
				// 更新本地存储的用户信息
				loginUser.name = name;
				// 只有修改了密码才需要重新登录
				if (password && newPassword) {
					// 重新登录
					$.ajax({
						url: baseUrl + '/fore/member/login',
						data: JSON.stringify({phone: phone, password: newPassword}),
						contentType: 'application/json; charset=UTF-8',
						type: 'post',
						dataType: 'JSON',
						success(loginResult) {
							if (loginResult.code == 200) {
								sessionStorage.setItem('token', loginResult.msg);
								sessionStorage.setItem('member', JSON.stringify(loginResult.data));
								loginUser = loginResult.data;
								// 刷新界面
								reloadMember();
								$('.dialog').remove();

								new bDialog().open({
									title: '成功',
									html: '修改成功，密码已更新！',
								});
							} else {
								// 登录失败，退出到未登录状态
								sessionStorage.removeItem('token');
								sessionStorage.removeItem('member');
								loginUser = null;
								reloadMember();
								$('.dialog').remove();

								new bDialog().open({
									title: '警告',
									html: '修改成功但新密码验证失败，请重新登录',
								});
							}
						}
					});
				} else {
					// 没有修改密码，直接更新本地信息
					sessionStorage.setItem('member', JSON.stringify(loginUser));
					reloadMember();
					$('.dialog').remove();

					new bDialog().open({
						title: '失败',
						html: '修改失败，必须输入原密码和新密码！',
					});
				}
			} else {
				new bDialog().open({
					title: '警告',
					html: result.msg || '修改失败',
				});
			}
		},
		error() {
			new bDialog().open({
				title: '错误',
				html: '服务器繁忙，修改失败',
			});
		}
	});

	return false;
});

// 显示错误提示
function showError(form, fieldName, message) {
	var formItem = form.find('[name="' + fieldName + '"]').closest('.form-item');
	formItem.addClass('error');

	// 如果还没有错误提示元素，则添加一个
	if (formItem.find('.error-message').length === 0) {
		formItem.append('<div class="error-message">' + message + '</div>');
	} else {
		formItem.find('.error-message').text(message);
	}
}

// 清除所有错误提示
function clearErrors(form) {
	form.find('.form-item').removeClass('error');
	form.find('.error-message').remove();
}

$('.add').click(function(){
	var dialog = new bDialog();
	dialog.open({
		title: '会员注册',
		html: $('#add').html(),

		opened: function() {
			// 清除可能的残留错误状态
			clearErrors($('.addForm'));
		}
	});
});

